/*
 * create by straysnail
 * 2022/2/26
 */
#include <Servo.h>  //引入舵机的库文件
Servo door_servo;  //创建一个舵机实例控制门的舵机
Servo window_servo;  //创建一个舵机实例控制窗的舵机
#define btnPin1 2 //按钮IO口
#define btnPin2 13
boolean btnVal1 = 0; //用于接收按钮的值
boolean btnVal2 = 0;
int count1 = 0;  //计算按钮被点击的次数
int count2 = 0;
boolean door_state = 0; //控制门的状态
boolean window_state = 0; //控制窗的状态

void setup() {
  Serial.begin(9600);
  pinMode(btnPin1,INPUT);
  pinMode(btnPin2,INPUT);
  door_servo.attach(11,500,2500);  //设置舵机的引脚为11，脉冲范围是500~2500ms
  window_servo.attach(4,500,2500);  //设置舵机的引脚为4，脉冲范围是500~2500ms
  door_servo.write(50); //初始化角度为50度
  delay(300);
  door_servo.write(140);   //舵机转到140度，开门
  delay(500);   //延时，给舵机转动的时间
  window_servo.write(116);
  delay(300);
  window_servo.write(50);  //开窗
  delay(500);
  door_servo.write(50); //关门
  delay(300);
  window_servo.write(116); //关窗
  delay(300);
}

void loop() {
  btnVal1 = digitalRead(btnPin1);  //读取按钮的值
  btnVal2 = digitalRead(btnPin2);
  if(btnVal1 == 0)  //如果按钮1被按下
  {
    delay(10); //消除按钮抖动引起的错误判断
    if(btnVal1 == 0)
    {
      boolean i1 = 1;
      while(i1 == 1)
      {
        btnVal1 = digitalRead(btnPin1);
        if(btnVal1 == 1)  //按钮1被松开
        {
          count1 = count1 + 1; //记下被点击的次数
          Serial.print("button1 = ");
          Serial.println(count1);
          door_state = count1 % 2; //求余数，得到奇数为1，偶数为0
          if(door_state == 1)
          {
            door_servo.write(140); //开门
            delay(300);
          }
          else
          {
            door_servo.write(50); //关门
            delay(300);
          }
          i1 = 0; //将i = 0，退出循环
        }
      }
    }
  }
  
  if(btnVal2 == 0)  //如果按钮2被按下
  {
    delay(10);
    if(btnVal2 == 0)
    {
      boolean i2 = 1;
      while(i2 == 1)
      {
        btnVal2 = digitalRead(btnPin2);
        if(btnVal2 == 1)  //按钮2被松开
        {
          count2 = count2 + 1; //记下被点击的次数
          Serial.print("button2 = ");
          Serial.println(count2);
          window_state = count2 % 2; //求余数，得到奇数为1，偶数为0
          if(window_state == 1)
          {
            window_servo.write(50); //开窗
            delay(300);
          }
          else
          {
            window_servo.write(116); //关窗
            delay(300);
          }
          i2 = 0; //将i = 0，退出循环
        }
      }
    }
  }
}
